package dm.api;

import java.util.Iterator;

import dm.api.filter.ViewFilter;
import dm.bsi.Container;
import dm.bsi.Deployment;
import dm.bsi.Image;
import dm.bsi.Node;
import indi.zjh.dp.access.Api;
import indi.zjh.dp.access.ApiContext;
import indi.zjh.dp.db.Configuration;
import indi.zjh.dp.db.Session;
import indi.zjh.dp.orm.Query;
import indi.zjh.dp.orm.Result;

public class GetDeploymentsApi extends Api {

	@Override
	public void process(ApiContext ctx) throws Exception {
		// TODO Auto-generated method stub
		Session session = Configuration.getSessionFactory().createSession();
		try
		{
			ViewFilter viewFilter = new ViewFilter(ctx);
			viewFilter.preprocess();

			Query<Deployment> query = new Query<Deployment>(session);
			Result<Deployment> result = query.find(Deployment.class).result();
			Iterator<Deployment> iter = result.iterator();
			
			viewFilter.writeResponse("name\tport");
			while(iter.hasNext())
			{
				Deployment deployment = iter.next();
				//Image image = (Image)session.getById(Image.class, deployment.getImage().iterator().next().longValue());
				//Container[] containers = deployment.getService(session).getRunningContainers(session);
				//viewFilter.writeResponse(deployment.getName()+"\t"+image.getName()+"\t"+deployment.getContainerExpectedCount()+"\t"+containers.length+"\t"+deployment.getHostPort());
				viewFilter.writeResponse(deployment.getName()+"\t"+deployment.getHostPort());
			}
			ctx.writeResponse("OK");
		}
		catch(Exception e)
		{
			ctx.writeResponse("FAIL");
			session.rollback();
			e.printStackTrace();
		}
		finally {
			session.close();
		}
	}

}
